/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Communication;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.logging.SocketHandler;

/**
 *
 * @author aaron
 */
public class JHaveSocketHandler extends SocketHandler {
    protected String serverId;
    public String getServerId() {
        return serverId;
    }

    public JHaveSocketHandler(String serverHost, int port, String serverId, boolean relogger) throws IOException {
        super(serverHost, port);
        this.serverId = serverId;
        this.setFormatter(relogger ? new JHaveSocketReloggerFormatter(serverId) : new JHaveSocketFormatter(serverId));
    }


    private static class JHaveSocketFormatter extends Formatter {
        protected String serverId;

        public JHaveSocketFormatter(String serverId) {
            super();
            this.serverId = serverId;
        }

        @Override
        public String format(LogRecord lr) {
            String formatStr = "%s %s: %s\n";
            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
            Date date = new Date(lr.getMillis());
            System.out.println("Formatting line");
            return String.format(formatStr, df.format(date), lr.getLevel().toString(), lr.getMessage());
        }

        @Override
        public String getHead(Handler hndlr) {
            //send the serverId as the first line to set up the LogServer thread.
            return String.format("%s\n", this.serverId);
        }
    }

    private static class JHaveSocketReloggerFormatter extends Formatter {

        protected String serverId;

        public JHaveSocketReloggerFormatter(String serverId) {
            super();
            this.serverId = serverId;
        }

        @Override
        public String getHead(Handler hndlr) {
            //send the serverId as the first line to set up the LogServer thread.
            return String.format("%s\n", this.serverId);
        }

        @Override
        public String format(LogRecord lr) {
            return lr.getMessage() + "\n";
        }
    }
}
